package com.studyyoun.android.nonghe.home.activity;
/**
 * Created by zhaolong on 2017/10/8.
 * 站在顶峰，看世界
 * 落在谷底，思人生
 */

import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.graphics.Color;
import android.graphics.PixelFormat;
import android.media.AudioManager;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.LinearInterpolator;
import android.view.animation.ScaleAnimation;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;

import com.studyyoun.android.androidcommonbaselibrary.activity.CommonBaseActivity;
import com.studyyoun.android.androidcommonbaselibrary.okhttp.callback.OkhttpCommonCallBack;
import com.studyyoun.android.androidcommonbaselibrary.okhttp.client.OkhttpCommonClient;
import com.studyyoun.android.androidcommonbaselibrary.utils.CommonLoadingUtils;
import com.studyyoun.android.androidcommonbaselibrary.utils.DateUtils;
import com.studyyoun.android.androidcommonbaselibrary.utils.LogUtils;
import com.studyyoun.android.androidcommonbaselibrary.utils.ToastUtils;
import com.studyyoun.android.androidcommonbaselibrary.view.DropDownSpringbackScrollView;
import com.studyyoun.android.androidcommonbaselibrary.view.VerticalSeekBar;
import com.studyyoun.android.nonghe.R;
import com.studyyoun.android.nonghe.home.model.VideoModel;
import com.studyyoun.android.nonghe.http.HttpUrlHelper;
import com.studyyoun.android.nonghe.welcom.CommonUserHelper;
import com.studyyoun.android.nonghe.welcom.model.UserModel;

import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

import io.vov.vitamio.MediaPlayer;
import io.vov.vitamio.Vitamio;
import io.vov.vitamio.widget.CenterLayout;

import static android.media.AudioManager.MODE_NORMAL;
import static android.media.AudioManager.STREAM_MUSIC;

/**
 * class infation
 */
public class VideoDetaileActivity extends CommonBaseActivity {
    private View mBackLinearLayout;
    private TextView mHeaderTitleTextView;
    private LinearLayout mHeaderTitleLayout;
    private VideoModel mVideoModel;
    private SurfaceView mPreview;
    private SurfaceHolder mHolder;

    private static final String TAG = "MediaPlayerDemo";
    private int mVideoWidth;
    private int mVideoHeight;
    private MediaPlayer mMediaPlayer;

    private boolean mIsVideoSizeKnown = false;
    private boolean mIsVideoReadyToBePlayed = false;
    private ImageView mVideoPauseImageView;
    private ImageView mVideoPlayImageView;
    private TextView mVideoTotalTimeTextView;
    private SeekBar mVideoPlaySeekBar;
    private TextView mVideoCurrentTimeTextView;
    private View mHeaderTitleLayout2;
    private TextView mHeaderTitleTextView2;
    private LinearLayout mVideoPlayControllLayout;
    private int mIsShowPlayControll = 0;
    private TextView mVideoDesTitleTextView;
    private TextView mVideoDesContentTextView;
    private DropDownSpringbackScrollView mVideoOtherInformationScrollView;
    private ImageView mVideoToFullScreeenImageView;
    /**
     * 1 竖屏
     * 2 横屏
     */
    private int mScreenType = 1;
    private LinearLayout mVideoMainLinearLayout;
    private LinearLayout mVideoCollectLinearLayout;
    private CenterLayout mVideoCenterLayout;
    private RelativeLayout mRootRelativeLayout;
    private ImageView mFullScreenPariseImageView;
    private TextView mSetVideoSpeedTextView;
    private ImageView mVideoVoiceImageView;
    private VerticalSeekBar mVideoVoiceSeekBar;

    private AudioManager mAudioManager;
    private LinearLayout mMinScreenPariseLayout;
    private ImageView mMinScreenPariseImageView;
    private TextView mMinScreenPariseTextView;
    private String mVideoId;
    private TextView mSeeVideoPeopCount;
    private LinearLayout mCollectVideoLayout;
    private ImageView mCollectImageView;
    private TextView mCollectTextView;

    @Override
    protected void getAllIntentExtraDatas(Intent intent) {
        mVideoModel = (VideoModel) intent.getSerializableExtra("videoModel");
        if (mVideoModel == null) {
            mVideoId = intent.getStringExtra("videoId");
        }
    }

    @Override
    protected int getCommonLayoutId() {
        return R.layout.activity_video_detaile_layout;
    }

    @Override
    protected void commonInitView(View view) {


        mRootRelativeLayout = findViewById(R.id.rl_root_view);

        mBackLinearLayout = findViewById(R.id.ll_base_back);
        mHeaderTitleLayout = findViewById(R.id.ll_base_header_title);
        mHeaderTitleLayout.setVisibility(View.GONE);
        mHeaderTitleTextView = findViewById(R.id.tv_base_header_title);

        //播放控制
        mHeaderTitleLayout2 = findViewById(R.id.ll_base_header_title2);
        mHeaderTitleLayout2.setVisibility(View.VISIBLE);
        mVideoPlayControllLayout = findViewById(R.id.ll_video_paly_controll);

        mHeaderTitleTextView2 = findViewById(R.id.tv_base_header_title2);


        //开始播放
        mVideoPlayImageView = findViewById(R.id.iv_video_play);
        //暂停播放
        mVideoPauseImageView = findViewById(R.id.iv_video_pause);
        //总时间
        mVideoTotalTimeTextView = findViewById(R.id.tv_video_total_time);
        mVideoCurrentTimeTextView = findViewById(R.id.tv_video_current_time);
        //播放进度
        mVideoPlaySeekBar = findViewById(R.id.sb_video_time);

        mVideoCenterLayout = findViewById(R.id.cl_video_main_content);

        mVideoDesTitleTextView = findViewById(R.id.tv_video_des_title);
        mVideoDesContentTextView = findViewById(R.id.tv_video_des_content);

        mVideoOtherInformationScrollView = findViewById(R.id.ddssv_video_other_information);

        mVideoToFullScreeenImageView = findViewById(R.id.iv_video_to_full_screen);
        mVideoMainLinearLayout = findViewById(R.id.ll_video_paly_main);
        //收藏视频
        mVideoCollectLinearLayout = findViewById(R.id.ll_video_coloect);

        mCollectVideoLayout = findViewById(R.id.ll_video_min_collect);
        mCollectImageView = findViewById(R.id.iv_video_min_collect);
        mCollectTextView = findViewById(R.id.tv_video_min_collect);


        //全屏下点赞按钮
        mFullScreenPariseImageView = findViewById(R.id.iv_full_screen_parise);
        mFullScreenPariseImageView.setVisibility(View.GONE);
        //小屏下的点赞按钮
        mMinScreenPariseLayout = findViewById(R.id.ll_video_min_parise);
        mMinScreenPariseImageView = findViewById(R.id.iv_video_min_parise);
        mMinScreenPariseTextView = findViewById(R.id.tv_video_min_parise);
        //全屏下设置播放速度
        mSetVideoSpeedTextView = findViewById(R.id.iv_full_screen_play_sped);
        mSetVideoSpeedTextView.setVisibility(View.GONE);

        //音量
        mVideoVoiceSeekBar = findViewById(R.id.sb_video_vicoe);
        mVideoVoiceSeekBar.setVisibility(View.GONE);


        mSeeVideoPeopCount = findViewById(R.id.tv_video_min_see);

        mVideoVoiceImageView = findViewById(R.id.iv_video_full_screen_video_voice);

        Vitamio.isInitialized(getApplicationContext());


        mPreview = findViewById(R.id.surface);
        mHolder = mPreview.getHolder();
        mHolder.addCallback(mSurfaceCallback);
        mHolder.setFormat(PixelFormat.RGBA_8888);

        mVideoWidth = mContext.getResources().getDisplayMetrics().widthPixels;
        mVideoHeight = (int) (mContext.getResources().getDisplayMetrics().scaledDensity * 220);
    }

    @Override
    protected void commonFunction() {

        mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);

        mAudioManager.setMode(MODE_NORMAL);
        //最大音量
        int maxVolume = mAudioManager.getStreamMaxVolume(STREAM_MUSIC);
        //当前音量
        int currentVolume = mAudioManager.getStreamVolume(STREAM_MUSIC);

        if (currentVolume == 0) {
            mVideoVoiceImageView.setImageDrawable(mContext.getResources().getDrawable(R.mipmap.video_voice_no));
        } else {
            mVideoVoiceImageView.setImageDrawable(mContext.getResources().getDrawable(R.mipmap.video_voice));
        }
        //音量进度设置
        mVideoVoiceSeekBar.setMax(100);
        mVideoVoiceSeekBar.setProgress((int) (100 * currentVolume * 1f / maxVolume));

        //返回键设置
        mBackLinearLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (VideoDetaileActivity.this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
                    VideoDetaileActivity.this.finish();
                } else {
                    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);//竖屏
                }

            }
        });

        setVideoModelInformationFunction();


    }

    private void setVideoModelInformationFunction() {
        if (mVideoModel != null) {
            mHeaderTitleTextView.setText(mVideoModel.getTitle());
            mHeaderTitleTextView2.setText(mVideoModel.getTitle());
            mVideoDesTitleTextView.setText("| " + mVideoModel.getTitle());
            mVideoDesContentTextView.setText(mVideoModel.getContent());
            mSeeVideoPeopCount.setText(mVideoModel.readCount+"人观看");


            List<String> pariseUserIdList = mVideoModel.getPariseUserIdList();
            if (pariseUserIdList != null) {
                UserModel userModel = CommonUserHelper.getUserModel();
                if (userModel != null) {
                    if (pariseUserIdList.contains(String.valueOf(userModel.getUserId()))) {
                        mMinScreenPariseTextView.setTextColor(Color.parseColor("#F5A623"));
                        mMinScreenPariseTextView.setText("已赞");
                        mMinScreenPariseImageView.setImageDrawable(getResources().getDrawable(R.mipmap.art_parise2));
                        mFullScreenPariseImageView.setImageDrawable(getResources().getDrawable(R.mipmap.art_parise2));
                    }
                }
            }

            List<String> collectUserIdList = mVideoModel.getCollectUserIdList();
            if (collectUserIdList != null) {
                UserModel userModel = CommonUserHelper.getUserModel();
                if (userModel != null) {
                    if (collectUserIdList.contains(String.valueOf(userModel.getUserId()))) {
                        mCollectTextView.setTextColor(Color.parseColor("#F5A623"));
                        mCollectTextView.setText("已收藏");
                        mCollectImageView.setImageDrawable(getResources().getDrawable(R.mipmap.my_cllect_icon4));
                    }
                }
            }
        }

    }

    @Override
    protected void commonDelayFunction() {

        mVideoPlayImageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                if (mMediaPlayer != null) {
                    if (mMediaPlayer.isPlaying()) {
                        mIsShowPlayControll = 0;
                        mMediaPlayer.pause();
                        mHandler.removeCallbacks(mVideoPlayCurrentTimeRunnable);
                        mVideoPlayImageView.setVisibility(View.GONE);
                        mVideoPauseImageView.setVisibility(View.VISIBLE);
                    }
                }
            }
        });

        mVideoPauseImageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (mMediaPlayer != null) {
                    mIsShowPlayControll = 0;
                    if (!mMediaPlayer.isPlaying()) {
                        mMediaPlayer.start();
                        mHandler.post(mVideoPlayCurrentTimeRunnable);
                        mVideoPlayImageView.setVisibility(View.VISIBLE);
                        mVideoPauseImageView.setVisibility(View.GONE);
                    }
                }
            }
        });

        mVideoPlaySeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int i, boolean isUser) {
                int progress = seekBar.getProgress();
                if (mMediaPlayer != null && isUser) {
                    mMediaPlayer.seekTo((long) (mMediaPlayer.getDuration() * (progress * 1f / seekBar.getMax())));
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
            }
        });

        mPreview.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (mIsShowPlayControll > 10) {
                    mIsShowPlayControll = 0;
                    showPlayControll();
                } else {
                    mIsShowPlayControll = 11;
                }
            }
        });

        mVideoToFullScreeenImageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (mScreenType == 1) {
                    mScreenType = 2;
                    //设置显示屏幕为横屏
                    if (VideoDetaileActivity.this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
                        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
                    }

                } else {
                    mScreenType = 1;
                    //设置显示屏幕为竖屏
                    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);//竖屏
                }
            }
        });

        mMinScreenPariseLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                LogUtils.d("点赞");

                UserModel userModel = CommonUserHelper.getUserModel();
                if (userModel != null) {
                    ScaleAnimation scaleAnimation = new ScaleAnimation(1.5f, 1f, 1.5f, 1f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
                    scaleAnimation.setDuration(400);
                    scaleAnimation.setInterpolator(new LinearInterpolator());
                    mMinScreenPariseImageView.startAnimation(scaleAnimation);

                    mMinScreenPariseTextView.setTextColor(Color.parseColor("#F5A623"));
                    mMinScreenPariseTextView.setText("已赞");
                    mMinScreenPariseImageView.setImageDrawable(getResources().getDrawable(R.mipmap.art_parise2));

                    addVideoPariseFunction();
                } else {
                    ToastUtils.show("请登录", mContext);
                }
            }
        });
        mFullScreenPariseImageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                LogUtils.d("点赞");
                UserModel userModel = CommonUserHelper.getUserModel();
                if (userModel != null) {
                    mFullScreenPariseImageView.setImageDrawable(getResources().getDrawable(R.mipmap.art_parise2));
                    addVideoPariseFunction();
                } else {
                    ToastUtils.show("请登录", mContext);
                }
            }
        });
        mCollectVideoLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                UserModel userModel = CommonUserHelper.getUserModel();
                if (userModel != null) {
                    ScaleAnimation scaleAnimation = new ScaleAnimation(1.5f, 1f, 1.5f, 1f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
                    scaleAnimation.setDuration(400);
                    scaleAnimation.setInterpolator(new LinearInterpolator());
                    mCollectImageView.startAnimation(scaleAnimation);

                    mCollectTextView.setTextColor(Color.parseColor("#F5A623"));
                    mCollectTextView.setText("已收藏");
                    mCollectImageView.setImageDrawable(getResources().getDrawable(R.mipmap.my_cllect_icon4));

                    addVideoCollectFunction();
                } else {
                    ToastUtils.show("请登录", mContext);
                }
            }
        });

        mSetVideoSpeedTextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String speedString = mSetVideoSpeedTextView.getText().toString();

                if (TextUtils.equals(speedString, "0.8x")) {
                    mSetVideoSpeedTextView.setText("1.0x");
                    mMediaPlayer.setPlaybackSpeed(1.0f);
                } else if (TextUtils.equals(speedString, "1.0x")) {
                    mSetVideoSpeedTextView.setText("1.25x");
                    mMediaPlayer.setPlaybackSpeed(1.25f);
                } else if (TextUtils.equals(speedString, "1.25x")) {
                    mSetVideoSpeedTextView.setText("1.5x");
                    mMediaPlayer.setPlaybackSpeed(1.5f);
                } else if (TextUtils.equals(speedString, "1.5x")) {
                    mSetVideoSpeedTextView.setText("1.75x");
                    mMediaPlayer.setPlaybackSpeed(1.75f);
                } else if (TextUtils.equals(speedString, "1.75x")) {
                    mSetVideoSpeedTextView.setText("2.0x");
                    mMediaPlayer.setPlaybackSpeed(2.0f);
                } else if (TextUtils.equals(speedString, "2.0x")) {
                    mSetVideoSpeedTextView.setText("0.8x");
                    mMediaPlayer.setPlaybackSpeed(0.8f);
                }
            }
        });

        mVideoVoiceImageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mIsShowPlayControll = 0;
                if (mVideoVoiceSeekBar.getVisibility() == View.GONE) {
                    mVideoVoiceSeekBar.setVisibility(View.VISIBLE);
                } else {
                    mVideoVoiceSeekBar.setVisibility(View.GONE);
                }
            }
        });

        mVideoVoiceSeekBar.setOnVerticalSeekBarChangeLiserner(new VerticalSeekBar.OnVerticalSeekBarChangeLiserner() {
            @Override
            public void onChange(SeekBar verticalSeekBar, int progress, int max) {
                LogUtils.d("音量大小设置");
                /**
                 * 直接设置音量大小
                 * 参数一：声音类型，STREAM_ALARM （警报）、STREAM_MUSIC （媒体音量）、STREAM_NOTIFICATION （窗口顶部状态栏Notification）、STREAM_RING （手机铃声）、STREAM_SYSTEM （系统）、STREAM_VOICE_CALL （通话）、STREAM_DTMF
                 * 参数二：想要调整的音量大小的数值
                 * 参数三：可选的标志位，FLAG_PLAY_SOUND 调整音量时播放声音，FLAG_SHOW_UI 调整时显示音量条,就是按音量键出现的那个，0 表示什么也没有
                 */
                mAudioManager.setStreamVolume(STREAM_MUSIC, (int) (mAudioManager.getStreamMaxVolume(STREAM_MUSIC) * (progress * 1f / max)), 0);
            }
        });

        //增加观看历史记录
        addVideoReadRecode();

    }

    /**
     * 对视频收藏
     */
    private void addVideoCollectFunction(){
        UserModel userModel = CommonUserHelper.getUserModel();
        if (userModel != null) {

            List<String> collectUserIdList = mVideoModel.getCollectUserIdList();
            if (collectUserIdList != null) {
                if (collectUserIdList.contains(String.valueOf(userModel.getUserId()))) {
                    ToastUtils.show("您已收藏过了", mContext);
                    return;
                }
            }


            String url = HttpUrlHelper.videoCollectUrl;
            ConcurrentHashMap<String, String> key = new ConcurrentHashMap<>();
            key.put("videoId", mVideoModel.getId() + "");
            key.put("userId", userModel.getUserId() + "");

            OkhttpCommonClient.sentPostRequest(url, key, new OkhttpCommonCallBack() {
                @Override
                public void onSuccess(Object obj) {
                    ToastUtils.show("收藏成功", mContext);
                }

                @Override
                public void onFaile(Object obj) {
                    ToastUtils.show("收藏失败", mContext);
                }
            });

        } else {
            ToastUtils.show("请登录", mContext);
        }
    }

    /**
     * 对视频点赞
     */
    private void addVideoPariseFunction() {

        UserModel userModel = CommonUserHelper.getUserModel();
        if (userModel != null) {

            List<String> pariseUserIdList = mVideoModel.getPariseUserIdList();
            if (pariseUserIdList != null) {
                if (pariseUserIdList.contains(String.valueOf(userModel.getUserId()))) {
                    ToastUtils.show("您已点过赞了", mContext);
                    return;
                }
            }


            String url = HttpUrlHelper.videoPairseUrl;
            ConcurrentHashMap<String, String> key = new ConcurrentHashMap<>();
            key.put("videoId", mVideoModel.getId() + "");
            key.put("userId", userModel.getUserId() + "");

            OkhttpCommonClient.sentPostRequest(url, key, new OkhttpCommonCallBack() {
                @Override
                public void onSuccess(Object obj) {
                    ToastUtils.show("点赞成功", mContext);
                }

                @Override
                public void onFaile(Object obj) {
                    ToastUtils.show("点赞失败", mContext);
                }
            });

        } else {
            ToastUtils.show("请登录", mContext);
        }


    }

    private long mPreLoadingLongTime = 0;
    private void addVideoReadRecode() {

        if (mVideoModel != null) {
            String url = HttpUrlHelper.sAddUserReadVideoRecodeFromIdUrl;

            ConcurrentHashMap<String, String> key = new ConcurrentHashMap<>();

            key.put("videoId", String.valueOf(mVideoModel.getId()));
            UserModel userModel = CommonUserHelper.getUserModel();
            if (userModel != null) {
                key.put("userId", String.valueOf(userModel.getUserId()));
            }

            OkhttpCommonClient.sentPostRequest(url, key, new OkhttpCommonCallBack() {
                @Override
                public void onSuccess(Object obj) {
                    LogUtils.d(" " + obj.toString());
                }

                @Override
                public void onFaile(Object obj) {
                    LogUtils.e("增加观看记录失败");
                }
            });

        }else {
            //获取视频详情
            if (!TextUtils.isEmpty(mVideoId)) {
                mPreLoadingLongTime=System.currentTimeMillis();
                CommonLoadingUtils.getInstance().showLoading(mHeaderTitleTextView);

                String url = HttpUrlHelper.sGetVideoDetaileUrl;

                ConcurrentHashMap<String, String> key = new ConcurrentHashMap<>();

                key.put("videoId", mVideoId);

                OkhttpCommonClient.sentPostRequest(url, key, new OkhttpCommonCallBack(VideoModel.class) {
                    @Override
                    public void onSuccess(Object obj) {
                        LogUtils.d(" " + obj.toString());

                        mVideoModel = (VideoModel) obj;


                        long flagTime = System.currentTimeMillis()-mPreLoadingLongTime;

                        if (flagTime<2000){
                            flagTime  = 2000 - flagTime;
                        }else {
                            flagTime=0;
                        }

                        if (mVideoModel != null) {
                            setVideoModelInformationFunction();
                            if (!mHolder.isCreating()) {
                                playVideo();
                            }
                        }
                        mHandler.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                CommonLoadingUtils.getInstance().closeFunction();
                                //增加观看历史记录
                                addVideoReadRecode();
                            }
                        }, flagTime);



                    }

                    @Override
                    public void onFaile(Object obj) {
                        LogUtils.e("增加观看记录失败");
                        ToastUtils.show("暂无视频详情",mContext);
                        CommonLoadingUtils.getInstance().closeFunction();
                    }
                });
            }else {
                ToastUtils.show("暂无视频详情",mContext);
                mHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        VideoDetaileActivity.this.finish();
                    }
                }, 1500);
            }
        }

    }

    private SurfaceHolder.Callback mSurfaceCallback = new SurfaceHolder.Callback() {
        @Override
        public void surfaceCreated(SurfaceHolder surfaceHolder) {
            LogUtils.d("surfaceCreated called");
            if (mVideoModel != null) {
                playVideo();
            }
        }

        @Override
        public void surfaceChanged(SurfaceHolder surfaceHolder, int i, int i1, int i2) {
            LogUtils.d("surfaceChanged called");
        }

        @Override
        public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
            LogUtils.d("surfaceDestroyed called");
        }
    };

    private MediaPlayer.OnBufferingUpdateListener mOnBufferingUpdateListener = new MediaPlayer.OnBufferingUpdateListener() {
        @Override
        public void onBufferingUpdate(MediaPlayer mp, int percent) {
            LogUtils.d("onBufferingUpdate percent:" + percent);
        }
    };
    private MediaPlayer.OnCompletionListener mOnCompletionListener = new MediaPlayer.OnCompletionListener() {
        @Override
        public void onCompletion(MediaPlayer mp) {
            LogUtils.d("onCompletion called");
        }
    };
    private MediaPlayer.OnPreparedListener mOnPreparedListener = new MediaPlayer.OnPreparedListener() {
        @Override
        public void onPrepared(MediaPlayer mp) {


            //总时间
            long duration = mp.getDuration();
            //设置总长度
            mVideoPlaySeekBar.setMax(100);
            //设置总时间
            mVideoTotalTimeTextView.setText(DateUtils.getInstance().formatTimeFunction(duration));
            LogUtils.d("onPrepared called" + duration);
            startVideoPlayback();

        }
    };
    private Runnable mVideoPlayCurrentTimeRunnable = new Runnable() {
        @Override
        public void run() {
            mIsShowPlayControll++;
            if (mIsShowPlayControll > 10) {
                hindPlayControll();
            }
            long currentPosition = mMediaPlayer.getCurrentPosition();
            mVideoPlaySeekBar.setProgress((int) (mVideoPlaySeekBar.getMax() * (currentPosition * 1f / mMediaPlayer.getDuration())));
            mVideoCurrentTimeTextView.setText(DateUtils.getInstance().formatTimeFunction(currentPosition));
            if (mMediaPlayer.getCurrentPosition() != mMediaPlayer.getDuration()) {
                mHandler.postDelayed(mVideoPlayCurrentTimeRunnable, 1000);
            }
        }
    };
    private MediaPlayer.OnVideoSizeChangedListener mOnVideoSizeChangedListener = new MediaPlayer.OnVideoSizeChangedListener() {
        @Override
        public void onVideoSizeChanged(MediaPlayer mp, int width, int height) {
            LogUtils.d("onVideoSizeChanged called");
            if (width == 0 || height == 0) {
                LogUtils.d("invalid video width(" + width + ") or height(" + height + ")");
                return;
            }
            mIsVideoSizeKnown = true;
            mVideoWidth = width;
            mVideoHeight = height;
            if (mIsVideoReadyToBePlayed && mIsVideoSizeKnown) {
                startVideoPlayback();
            }
        }
    };

    private MediaPlayer.OnErrorListener mOnErrorListener = new MediaPlayer.OnErrorListener() {
        @Override
        public boolean onError(MediaPlayer mp, int what, int extra) {
            ToastUtils.show("播放视频异常:" + what + "-" + extra, mContext);
            return false;
        }
    };

    private void playVideo() {
        doCleanUp();
        try {
            mMediaPlayer = new MediaPlayer(this);
            mMediaPlayer.setDataSource(mVideoModel.getVideoUrl());
            mMediaPlayer.setDisplay(mHolder);
            mMediaPlayer.prepare();
            mMediaPlayer.setOnBufferingUpdateListener(mOnBufferingUpdateListener);
            mMediaPlayer.setOnCompletionListener(mOnCompletionListener);
            mMediaPlayer.setOnPreparedListener(mOnPreparedListener);
            mMediaPlayer.setOnVideoSizeChangedListener(mOnVideoSizeChangedListener);
            mMediaPlayer.setOnErrorListener(mOnErrorListener);
            setVolumeControlStream(STREAM_MUSIC);
        } catch (Exception e) {
            LogUtils.e("error: " + e.getMessage());
        }
    }


    @Override
    protected void onPause() {
        super.onPause();
        releaseMediaPlayer();
        doCleanUp();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        releaseMediaPlayer();
        doCleanUp();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);

        // Checks the orientation of the screen
        if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
            FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) mVideoCenterLayout.getLayoutParams();
            if (layoutParams != null) {


                //横屏状态下

                mSetVideoSpeedTextView.setVisibility(View.VISIBLE);
                mVideoOtherInformationScrollView.setVisibility(View.GONE);
                mVideoCollectLinearLayout.setVisibility(View.GONE);
                mFullScreenPariseImageView.setVisibility(View.VISIBLE);
                mVideoToFullScreeenImageView.setImageDrawable(mContext.getResources().getDrawable(R.mipmap.video_to_min_screen));

                mVideoWidth = mContext.getResources().getDisplayMetrics().widthPixels;
                mVideoHeight = (int) (mContext.getResources().getDisplayMetrics().heightPixels);
                layoutParams.width = mVideoWidth;
                layoutParams.height = mVideoHeight;
                mVideoCenterLayout.setLayoutParams(layoutParams);
                //重设视频大小
                mHolder.setFixedSize(mVideoWidth, mVideoHeight);
                //隐藏状态栏
                mHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        mRootRelativeLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN);
                    }
                }, 400);

            }

        } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
            FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) mVideoCenterLayout.getLayoutParams();

            //竖屏状态下
            //播放速度
            mSetVideoSpeedTextView.setVisibility(View.GONE);
            mFullScreenPariseImageView.setVisibility(View.GONE);
            mVideoCollectLinearLayout.setVisibility(View.VISIBLE);
            mVideoToFullScreeenImageView.setImageDrawable(mContext.getResources().getDrawable(R.mipmap.video_to_full_screen));
            mVideoOtherInformationScrollView.setVisibility(View.VISIBLE);

            if (layoutParams != null) {

                mVideoWidth = mContext.getResources().getDisplayMetrics().widthPixels;
                mVideoHeight = (int) (mContext.getResources().getDisplayMetrics().scaledDensity * 200);
                layoutParams.width = mVideoWidth;
                layoutParams.height = mVideoHeight;
                mVideoCenterLayout.setLayoutParams(layoutParams);

                mHolder.setFixedSize(mVideoWidth, mVideoHeight);
                mHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        mRootRelativeLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_VISIBLE);
                    }
                }, 400);

            }
        }
    }

    private void releaseMediaPlayer() {
        if (mMediaPlayer != null) {
            mMediaPlayer.release();
            mMediaPlayer = null;
        }
    }

    private void doCleanUp() {
        mHandler.removeCallbacks(mVideoPlayCurrentTimeRunnable);
        mVideoWidth = 0;
        mVideoHeight = 0;
        mIsVideoReadyToBePlayed = false;
        mIsVideoSizeKnown = false;

    }

    private void startVideoPlayback() {
        LogUtils.d("startVideoPlayback");
        mHolder.setFixedSize(mVideoWidth, mVideoHeight);
        mMediaPlayer.start();
        mHandler.post(mVideoPlayCurrentTimeRunnable);


    }

    private void showPlayControll() {
        mHeaderTitleLayout2.setVisibility(View.VISIBLE);
        mVideoPlayControllLayout.setVisibility(View.VISIBLE);

        if (mScreenType == 2) {
            //横屏下
            mSetVideoSpeedTextView.setVisibility(View.VISIBLE);
            mFullScreenPariseImageView.setVisibility(View.VISIBLE);
        }
    }

    private void hindPlayControll() {
        mHeaderTitleLayout2.setVisibility(View.GONE);
        mVideoPlayControllLayout.setVisibility(View.GONE);
        //音量
        mVideoVoiceSeekBar.setVisibility(View.GONE);

        if (mScreenType == 2) {
            //横屏下
            mSetVideoSpeedTextView.setVisibility(View.GONE);
            mFullScreenPariseImageView.setVisibility(View.GONE);
        }
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        switch (keyCode) {

            case KeyEvent.KEYCODE_VOLUME_DOWN:
                LogUtils.d("KEYCODE_VOLUME_DOWN");
            case KeyEvent.KEYCODE_VOLUME_UP:
                LogUtils.d("KEYCODE_VOLUME_UP");
                //最大音量
                int maxVolume = mAudioManager.getStreamMaxVolume(STREAM_MUSIC);
                //当前音量
                int currentVolume = mAudioManager.getStreamVolume(STREAM_MUSIC);
                mVideoVoiceSeekBar.setMax(100);
                mVideoVoiceSeekBar.setProgress((int) (100 * currentVolume * 1f / maxVolume));

                if (currentVolume == 0) {
                    mVideoVoiceImageView.setImageDrawable(mContext.getResources().getDrawable(R.mipmap.video_voice_no));
                } else {
                    mVideoVoiceImageView.setImageDrawable(mContext.getResources().getDrawable(R.mipmap.video_voice));
                }


                break;
            case KeyEvent.KEYCODE_VOLUME_MUTE:

                return true;
            case KeyEvent.KEYCODE_BACK:
                if (VideoDetaileActivity.this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
                    VideoDetaileActivity.this.finish();
                } else {
                    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);//竖屏
                }
                return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}
